'use strict';

/**
 * copyright (c) 2017-2023 厦门风领科技有限公司
 * https://www.fengling.cn/
 * 
 * 初始化UI管理器
 * zengbinsi
 * 2020-08-24
 */


import os from 'os';
import path from 'path';
import pathUtil from '../libs/utils/path-utils';
import fileUtil from '../libs/utils/file-utils';
import { callSequence } from '../libs/utils/function-call-seq';
import { getTimeFormat } from '../libs/utils/date-time-utils';
import uuidUtils from '../libs/utils/uuid-utils';
const srcPath = pathUtil.getPathInTemplateAssets(path.join('bundles', 'framework', 'ui', 'uimanager'));
const dstPath = pathUtil.getPathInAssets(path.join('bundles', 'framework', 'ui', 'uimanager'));

const updateDir = async (callback?: Function) => {
    await pathUtil.refreshAsset('db://assets/bundles/framework/ui/uimanager/');
    console.log('[tool-box]bundles/framework/ui/uimanager/ refreshed!');
    callback && callback();
};

// 初始化目录
const initDir = (callback?: Function) => {
    pathUtil.mkdirsSyncInAssets(path.join('bundles', 'framework', 'ui', 'uimanager'), callback);
};

/** 新建UI面板 */
const newUIPanelFn = (uiName: string, callback?: Function) => {
    let filePath = uiName;
    const arr = uiName.split('/');
    uiName = arr[arr.length - 1];

    let uiPath = 'bundles/ui';
    filePath = path.join('bundles', 'ui');
    for (let i = 0; i < arr.length - 1; i++) {
        uiPath += `/${arr[i]}`;
        filePath = path.join(filePath, arr[i]);
    }
    
    // 创建脚本文件
    pathUtil.mkdirsSyncInAssets(uiPath, async () => {
        const now = new Date();
        // 代码脚本
        let srcFile = path.join(pathUtil.pathTemplateAssets, 'bundles', 'ui', 'TemplatePanel.tsz');
        let distFile = path.join(pathUtil.pathAssets, filePath, `${uiName}.ts`);
        const uuid = uuidUtils.getUUIDV4();
        if (!fileUtil.existsSync(distFile)) {
            // ts脚本文件
            const hostname = os.hostname();
            let data = fileUtil.readFileSync(srcFile);
            data = data.replace('-2021 厦门', `-${now.getFullYear()} 厦门`);
            data = data.replace('开发者', hostname.substr(0, hostname.indexOf('deMacBook')).replace('cengbinsi', 'zengbinsi'));
            data = data.replace('yyyy-mm-dd', `${getTimeFormat(now)}`);
            data = data.replace('TemplatePanel', uiName);
            fileUtil.writeFileSync(distFile, data);

            // 代码脚本对应的meta文件
            srcFile = path.join(pathUtil.pathTemplateAssets, 'bundles', 'ui', 'TemplatePanel.ts.meta');
            distFile = path.join(pathUtil.pathAssets, filePath, `${uiName}.ts.meta`);
            data = fileUtil.readFileSync(srcFile);
            data = data.replace('新的UUID', uuid);
            fileUtil.writeFileSync(distFile, data);
            console.log(`[tool-box]new script ${uiPath}/${uiName}.ts successed!`);
        } else {
            console.warn(`[tool-box]new script ${uiPath}/${uiName}.ts exists!`);
        }

        // 面板预制体
        srcFile = path.join(pathUtil.pathTemplateAssets, 'bundles', 'ui', 'TemplatePanel.prefab');
        distFile = path.join(pathUtil.pathAssets, filePath, `${uiName}.prefab`);
        if (!fileUtil.existsSync(distFile)) {
            let data = fileUtil.readFileSync(srcFile);
            data = data.replace('TemplatePanel', uiName);
            data = data.replace('组件uuid对应的code', Editor.Utils.UUID.compressUUID(uuid, true));
            fileUtil.writeFileSync(distFile, data);

            console.log(`[tool-box]new script ${uiPath}/${uiName}.prefab successed!`);
            await pathUtil.refreshAsset(`db://assets/${uiPath}/${uiName}.ts`);
            console.log(`[tool-box]${uiPath}/${uiName}.ts refreshed!`);
            await pathUtil.refreshAsset(`db://assets/${uiPath}/${uiName}.prefab`);
            console.log(`[tool-box]${uiPath}/${uiName}.prefab refreshed!`)
        } else {
            console.warn(`[tool-box]new script ${uiPath}/${uiName}.prefab exists!`);
        }

        callback && callback();
    });
};

const initUIManager = async (callback?: Function) => {
    console.log(`[tool-box]import UIManager.ts...`);
    fileUtil.copy(path.join(srcPath, 'UIManager.tsz'), path.join(dstPath, 'UIManager.ts'));
    await pathUtil.refreshAsset(`db://assets/bundles/framework/ui/uimanager/UIManager.ts`);
    console.log(`[tool-box]import UIManager.ts successed!`);
    callback && callback();
};

const initUIManagerMachine = async (callback?: Function) => {
    console.log(`[tool-box]import UIManagerMachine.ts...`);
    fileUtil.copy(path.join(srcPath, 'UIManagerMachine.tsz'), path.join(dstPath, 'UIManagerMachine.ts'));
    await pathUtil.refreshAsset(`db://assets/bundles/framework/ui/uimanager/UIManagerMachine.ts`);
    console.log(`[tool-box]import UIManagerMachine.ts successed!`);
    callback && callback();
};

const initFileUIManagerFn = (callback?: Function) => {
    const initDirLoading = async (cb0?: Function)=>{
        pathUtil.mkPathSync(pathUtil.getPathInAssets(path.join('bundles', 'ui', 'loading')));
        const srcPath = pathUtil.getPathInTemplateAssets(path.join('bundles', 'ui', 'loading.meta'));
        const dstPath = pathUtil.getPathInAssets(path.join('bundles', 'ui', 'loading.meta'));
        fileUtil.copy(srcPath, dstPath, true);
        await pathUtil.refreshAsset(`db://assets`);
        cb0 && cb0();
    };
    return callSequence([initDir, initDirLoading, (cb?: Function) => {
        newUIPanelFn('loading/FLoadingMaskPanel');
        cb && cb();
    }, initUIManager, callback]);
};

export const initFileUIManagerMachine = (callback?: Function) => {
    return callSequence([initDir, initFileUIManagerFn, initUIManagerMachine, updateDir, callback]);
};

export const newUIPanel = newUIPanelFn;
export const initFileUIManager = initFileUIManagerFn;